﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using AutoMapper.QueryableExtensions;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Mapper.Initialize(r =>
            {
                r.CreateMap<Users, UsersDto>();
                r.CreateMap<Student, StudentDto>();
            });


            using (MyContext context = new MyContext())
            {
                context.Database.Migrate();
            }

            using (MyContext context = new MyContext())
            {
                if (!context.Students.Any(r => r.Id == "laowang111"))
                {
                    context.Students.Add(new Student
                    {
                        ClassName = "1年级1班",
                        Id = "laowang111",
                        User = new Users
                        {
                            Id = "laowang111111",
                            Name = "老王",
                        }
                    });
                    context.SaveChanges();
                }

                var result = context.Students.ProjectTo<StudentDto>().ToList();

                Console.WriteLine(JsonConvert.SerializeObject(result));
            }
        }
    }

    public class MyContext : DbContext
    {
        public DbSet<Users> Users { get; set; }

        public DbSet<Student> Students { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=testautomapper;Integrated Security=True");
            optionsBuilder.UseMySQL("server=localhost;user id=root;password=123123;persistsecurityinfo=True;SslMode=None;database=demo");

            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }

    [Table("Users")]
    public class Users
    {
        [Key, StringLength(36)]
        public string Id { get; set; }

        public string Name { get; set; }

    }

    [Table("Student")]
    public class Student
    {
        [Key, StringLength(36)]
        public string Id { get; set; }

        public string ClassName { get; set; }

        [ForeignKey("UserId")]
        public Users User { get; set; }

        public string UserId { get; set; }
    }

    public class UsersDto
    {

        public string Name { get; set; }

    }


    public class StudentDto
    {

        public string ClassName { get; set; }

        public UsersDto User { get; set; }

        public string UserName { get; set; }
    }
}
